import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message, Radio } from 'antd';
import './style.scss';
import { useForm } from 'antd/lib/form/Form';
import { Store } from 'antd/lib/form/interface';

import { clearNull, verifyNull } from 'utils/tools';
import { AddExtendQuestionRequest, ModifyExtendQuestionRequest } from 'admin/schema/ExtendQuestion';
import { addExtendQuestion, modifyExtendQuestion } from 'admin/servers/servers';
import { StrictLevelSelect } from '../StrictLevelSelect';

type Props = {
  /**
   * 显示/隐藏弹窗
   */
  show: boolean;
  /**
   * 意图Id(问答Id)
   */
  intentionId: number;
  /**
   * 编辑扩展-初始数据
   */
  extendProp?: ModifyExtendQuestionRequest;
  /**
   * 关闭弹窗事件
   */
  onClose: () => void;
  /**
   * 新建和编辑成功，传回扩展问题Id和Name，继续发现新词逻辑
   */
  onSuccess: (obj?: any) => void;
};

/**
 * 创建扩展组件
 * 示例：AI管理-机器人管理-版本管理-配置话术流程-问答库-编辑-新建扩展
 */
const ExtendQuestionModel: React.FC<Props> = ({
  show,
  intentionId,
  extendProp,
  onClose,
  onSuccess,
}) => {
  const [form] = useForm();
  // 弹窗类型：0-新建，1-编辑
  const [drawerMode, setDrawerMode] = useState<0 | 1>(0);
  // 确定按钮loading
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  /**
   * 表单赋值&初始化
   */
  useEffect(() => {
    if (!show) {
      return;
    }
    if (extendProp) {
      console.log('编辑扩展问', intentionId, extendProp);
      // 编辑弹窗-根据props属性，设置默认值
      setDrawerMode(1);
      const { extendQuestionName, extendType, strictExclusion, strictnessLevel } = extendProp;
      form.setFieldsValue({
        extendQuestionName,
        extendType,
        strictExclusion,
        strictnessLevel,
      });
    } else {
      setDrawerMode(0);
      console.log('新建扩展问', intentionId, extendProp);
    }
  }, [extendProp, form, intentionId, show]);

  /**
   * 确认
   */
  const onFinish = async (values: Store) => {
    console.log('onFinish -> values', values);
    setConfirmLoading(true);
    const { extendQuestionName, extendType, strictExclusion, strictnessLevel } = values;
    try {
      let res: any;
      if (drawerMode) {
        // 编辑
        const param: ModifyExtendQuestionRequest = clearNull({
          extendQuestionId: extendProp?.extendQuestionId,
          extendQuestionName,
          extendType,
          strictExclusion,
          strictnessLevel,
        });
        console.log('编辑-param', param);
        res = await modifyExtendQuestion(param);
      } else {
        // 新建
        const param: AddExtendQuestionRequest = clearNull({
          intentionId: Number(intentionId),
          extendQuestionName,
          extendType,
          strictExclusion,
          strictnessLevel,
        });
        console.log('新建-param', param);
        res = await addExtendQuestion(param);
      }
      // 请求成功
      form.resetFields();
      const str = drawerMode ? '编辑成功' : '创建成功';
      message.success(str);
      onSuccess({
        extendQuestionId: drawerMode ? extendProp?.extendQuestionId : res.data.extendQuestionId,
        extendQuestionName,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setConfirmLoading(false);
  };

  /**关闭弹窗 */
  const closeDrawer = () => {
    form.resetFields();
    onClose();
    setConfirmLoading(false);
  };

  return (
    <>
      <Modal
        title={drawerMode ? '编辑扩展' : '新建扩展'}
        visible={show}
        onOk={() => {
          form.submit();
        }}
        confirmLoading={confirmLoading}
        onCancel={closeDrawer}
        destroyOnClose
      >
        <Form
          layout="horizontal"
          labelCol={{ span: 5 }}
          form={form}
          initialValues={{
            extendQuestionName: '',
            extendType: 0,
            strictExclusion: 0,
            strictnessLevel: 3,
          }}
          onFinish={onFinish}
        >
          {!drawerMode && (
            <Form.Item label="扩展类型" name="extendType" rules={verifyNull('请选择扩展类型')}>
              <Radio.Group disabled={!!drawerMode}>
                <Radio value={0}>同义</Radio>
                <Radio value={1}>排除</Radio>
              </Radio.Group>
            </Form.Item>
          )}
          <Form.Item noStyle dependencies={['extendType']}>
            {({ getFieldValue }) => {
              const type = getFieldValue('extendType');
              return type === 1 ? (
                <Form.Item
                  label="严格排除"
                  name="strictExclusion"
                  rules={verifyNull('请选择是否严格排除')}
                >
                  <Radio.Group>
                    <Radio value={1}>是</Radio>
                    <Radio value={0}>否</Radio>
                  </Radio.Group>
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          <Form.Item
            label="扩展问题"
            name="extendQuestionName"
            rules={[{ required: true, whitespace: true }]}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <Input.TextArea placeholder="请输入扩展问题" maxLength={200} />
          </Form.Item>
          <Form.Item noStyle dependencies={['extendType']}>
            {({ getFieldValue }) => {
              // 扩展问类型
              const type = getFieldValue('extendType');
              // 严格度展示值
              const currentVal = getFieldValue('strictnessLevel');
              return type === 0 ? (
                <Form.Item label="匹配严格度" required>
                  <StrictLevelSelect
                    currentValue={currentVal}
                    onChange={(val: number) => {
                      // 修改表单值
                      form.setFieldsValue({
                        strictnessLevel: val,
                      });
                    }}
                  />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default ExtendQuestionModel;
